#!/usr/bin/env bash
# Nautilus right-click action: zip the selection, then hand the archive off
# to the Tailscale GNOME extension via DBus (same native picker as the
# Quick Settings "Send file" entry).

set -eu

LOG_TAG="tailscale-taildrop"

notify_ok()   { notify-send -a "Tailscale" -i tailscale-symbolic           "Tailscale" "$1" || true; }
notify_err()  { notify-send -a "Tailscale" -i tailscale-symbolic -u critical "Tailscale" "$1" || true; }
log_err()     { logger -t "$LOG_TAG" -p user.err -- "$1" || true; }

if [ "$#" -eq 0 ]; then
    notify_err "Send with Taildrop (ZIP): no files selected."
    exit 1
fi

TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT

# Archive name = first selection + timestamp, so the receiver gets a hint.
FIRST_NAME=$(basename -- "$1")
ZIP_NAME="${FIRST_NAME%.*}-$(date +%Y%m%d-%H%M%S).zip"
ZIP_PATH="$TMPDIR/$ZIP_NAME"

# Add each item with its basename only (clean entry names in the archive).
for f in "$@"; do
    dir=$(dirname -- "$f")
    base=$(basename -- "$f")
    if ! err=$( ( cd "$dir" && zip -qr "$ZIP_PATH" "$base" ) 2>&1 ); then
        log_err "zip failed for $base: $err"
        notify_err "Failed to create archive ($base)."
        exit 1
    fi
done

esc=${ZIP_PATH//\\/\\\\}
esc=${esc//\"/\\\"}
if ! err=$(gdbus call --session \
        --dest org.gnome.Shell \
        --object-path /org/gnome/Shell/Extensions/TailscaleGnome \
        --method org.gnome.Shell.Extensions.TailscaleGnome.SendFiles \
        "[\"$esc\"]" 2>&1); then
    log_err "DBus SendFiles failed: $err"
    notify_err "Tailscale GNOME extension is not running or DBus call failed."
    exit 1
fi
